//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.lujieni.springbootmybatis.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.lujieni.springbootmybatis.po.BasicEntity;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

/**
 * 自动填充字段实现类
 * 自动填充功能通过实现 com.baomidou.mybatisplus.core.handlers.MetaObjectHandler 接口来实现。
 * 你需要创建一个类来实现这个接口，并在其中定义插入和更新时的填充逻辑。
 * 确保你的 MyMetaObjectHandler 类被 Spring 管理，可以通过 @Component
 */
@Component
public class CmclinkDbFieldHandler implements MetaObjectHandler {
    public CmclinkDbFieldHandler() {
    }

    /**
     * 字段上配了 FieldFill.INSERT,这里赋值才有效
     * @param metaObject 元对象
     */
    public void insertFill(MetaObject metaObject) {
        if (Objects.nonNull(metaObject) && metaObject.getOriginalObject() instanceof BasicEntity) {
            BasicEntity basicEntity = (BasicEntity)metaObject.getOriginalObject();
            Date now = new Date();
            if (Objects.isNull(basicEntity.getCreateTime())) {
                basicEntity.setCreateTime(now);
            }

            if (Objects.isNull(basicEntity.getModifyTime())) {
                basicEntity.setModifyTime(now);
            }

            if (Objects.isNull(basicEntity.getCreateUserCode())) {
                basicEntity.setCreateUserCode("181268");
            }

            if (Objects.isNull(basicEntity.getModifyUserCode())) {
                basicEntity.setModifyUserCode("181268");
            }
        }

    }

    public void updateFill(MetaObject metaObject) {
        Object modifyTime = this.getFieldValByName("modifyTime", metaObject);
        if (Objects.isNull(modifyTime)) {
            this.setFieldValByName("modifyTime", new Date(), metaObject);
        }

        Object modifier = this.getFieldValByName("modifyUserCode", metaObject);
        if (Objects.isNull(modifier)) {
            this.setFieldValByName("modifyUserCode", "181268", metaObject);
        }

    }
}
